import {
	WEBSOCKET_URL
} from "@/common/common.js";

export default class WebSocketService {
	constructor() {
		this.ws = null;
		this.targetGroupId = null;
		this.targetUserId = null;
		this.currentUserId = null;
		const iMMsgs = uni.getStorageSync('IMMsgs');
		if (iMMsgs == '') {
			console.log("init iMMsgs...")
			let IMMsgs = []
			uni.setStorageSync('IMMsgs', IMMsgs);
		}
		this.iMMsgs = uni.getStorageSync('IMMsgs');
		// 清理
		// this.clearAllMsgs();
	}

	swichGroupAndUser(groupId, userId) {
		this.targetGroupId = groupId;
		this.targetUserId = userId;
	}
	
	clearConversation(groupId) {
		let iMMsgs = uni.getStorageSync('IMMsgs');
		iMMsgs = iMMsgs.filter(item => item.content != groupId);
		uni.setStorageSync('IMMsgs', IMMsgs);
		this.iMMsgs = uni.getStorageSync('IMMsgs');
	}

	clearAllMsgs() {
		let IMMsgs = []
		uni.setStorageSync('IMMsgs', IMMsgs);
		this.iMMsgs = uni.getStorageSync('IMMsgs');
	}
	
	updateMsgRead(groupId) {
		let iMMsgs = uni.getStorageSync('IMMsgs');
		iMMsgs.forEach(item => {
			if (item.groupId == groupId) {
				item.satus = 1
			}
		});
		uni.setStorageSync('IMMsgs', iMMsgs);
		this.iMMsgs = uni.getStorageSync('IMMsgs');
	}

	connect(userId) {
		this.currentUserId = userId
		if (this.ws && this.ws.readyState === 1) { // 已连接
			console.log('已连接');
			return;
		}
		console.log("start connect")
		const ws = uni.connectSocket({
			url: WEBSOCKET_URL,
			success() {
				console.log('WebSocket连接成功');
			}
		});
		ws.onOpen(() => {
			console.log('WebSocket连接已打开！');
			this.preSendMessage(userId);
			console.log('WebSocket登录');
		});

		ws.onMessage((res) => {
			console.log('收到服务器内容：' + res.data);
			let message = JSON.parse(res.data);
			let iMMsgs = this.iMMsgs
			if (Array.isArray(message)) {
				message.forEach(o => {
					o.satus = 0;
					o.createTime = this.coverDate(o.createTime);
					iMMsgs.push(o)
				})
			} else {
				// 当前会话 || 自己发的
				if (message.groupId == this.targetGroupId || this.currentUserId == message.fromUser) {
					message.satus = 1; // 已读
					console.log(message)
					console.log("已读")
				} else {
					message.satus = 0;
					console.log("未读")
				}
				message.createTime = this.coverDate(message.createTime);				

				iMMsgs.push(message);
				this.handleMessage(message);
			}
			this.iMMsgs = iMMsgs
			uni.setStorageSync('IMMsgs', this.iMMsgs);
		});

		ws.onError((error) => {
			console.error('WebSocket 错误', error);
		});

		ws.onClose(() => {
			console.log('WebSocket 已关闭！');
		});
		this.ws = ws

	}

	coverDate(str) {
		if (str == null) {
			return null;
		}
		if (str == '') {
			return null;
		}
		let date = new Date(str);
		let year = date.getFullYear();
		let month = (date.getMonth() + 1).toString().padStart(2, '0');
		let day = date.getDate().toString().padStart(2, '0');
		let hours = date.getHours().toString().padStart(2, '0');
		let minutes = date.getMinutes().toString().padStart(2, '0');
		let seconds = date.getSeconds().toString().padStart(2, '0');

		return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
	}

	handleMessage(data) {
		// 这里是处理消息的逻辑，可以根据需要进行扩展
		console.log('接收到消息:', data);
		// 触发全局事件
		uni.$emit('WebSocketMessage', data);
	}

	send(data) {
		if (this.ws) {
			this.ws.send({
				data: JSON.stringify(data),
				success: () => {
					console.log('信息发送成功');
				},
				fail: (error) => {
					console.error('信息发送失败', error);
				}
			});
		} else {
			console.error('WebSocket连接未打开');
		}
	}

	close() {
		if (this.ws) {
			this.ws.close();
		}
	}

	preSendMessage(userId) {
		if (this.ws) {
			let message = {
				action: 'login',
				from: userId
			}
			this.ws.send({
				data: JSON.stringify(message),
				success: () => {
					console.log('预信息发送成功');
				},
				fail: (error) => {
					console.error('预信息发送失败', error);
				}
			});
		}
	}

	parseDate(timeString) {
		const parts = timeString.split('-');
		const year = parseInt(parts[0], 10);
		const month = parseInt(parts[1], 10) - 1;
		const day = parseInt(parts[2], 10);
		return new Date(year, month, day);
	}

}